﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ObjectRelationalMap.Models;

namespace Presentation.ViewModels
{
    class ShellViewModel
    {
        Data.Sources.IDataSource _dataSource;
        ORM _models;

        public ListAnecdotesViewModel AnecdotalList { get; set; }

        public ShellViewModel()
        {
            _models = new ORM();

            if (AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData != null
               && AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData.Length > 0)
            {
                try
                {
                    string uriString = AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData[0];
                    Uri uri = new Uri(uriString);

                    _dataSource = new Data.Sources.File(uri.LocalPath);

                    _models.LoadRelationalData(_dataSource);
                }
                catch
                {
                }
            }

            AnecdotalList = new ListAnecdotesViewModel(_models);
        }

        public IEnumerable<Caliburn.Micro.IResult> Save()
        {
            GetFilePath saveFilePath = new GetFilePath(GetFilePath.FileDialogTypes.Save) { DefaultExt = "ant", Filter = "*.ant|*.*" };  
            yield return saveFilePath;  
  
            if (saveFilePath.FilePath == null) yield break; //null means the user clicked ‘Cancel’
            
            _dataSource = new Data.Sources.File(saveFilePath.FilePath);

            _dataSource.SaveData(_models.ToRelationalData());
        }

        public IEnumerable<Caliburn.Micro.IResult> Open()
        {
            GetFilePath openFilePath = new GetFilePath(GetFilePath.FileDialogTypes.Open) { DefaultExt = "ant", Filter = "*.ant|*.*" };
            yield return openFilePath;

            if (openFilePath.FilePath == null) yield break; //null means the user clicked ‘Cancel’

            _dataSource = new Data.Sources.File(openFilePath.FilePath);

            _models.LoadRelationalData(_dataSource);

            yield break;
        }
    }
}
